package gameLogic

import (
	"net"
	"server_cluster/chat/chat_config"
	"server_cluster/chat/db"
	"server_cluster/chat/sharemem"
	"server_cluster/common/config"
	"server_cluster/common/logger"
	"server_cluster/common/mysock"
	"server_cluster/common/protoc/pb"
	"server_cluster/common/sharedb"

	"google.golang.org/protobuf/proto"
	// "server_cluster/common/tools"
)

func SyncStock() {
	cfg := sharedb.Config_server{}
	if !cfg.Update_stock(db.Conn, int16(chat_config.CONF.SERVER_ID), sharemem.Myshm.Stock) {
		logger.Error("update stock error.server id = %d", chat_config.CONF.SERVER_ID)
	}
}

func ServerAction(conn net.Conn, mybuf *mysock.SockBuf, fd int32) {
	defer func() {
		if err := recover(); err != nil {
			logger.Error("!!! GAME MAIN LOOP PANIC !!!")
			logger.Error("error: %v", err)
			logger.Error("stack: %v", logger.Stack())
		}
	}()
	if mybuf.Command == config.CSC_Heart {
		return
	}
	var shm_user *sharemem.ShmUser

	if mybuf.Command != config.SC_CREATE_BATTLE {
		shm_user = sharemem.GetShmUserByUid(int64(mybuf.Session))
		if shm_user == nil {
			logger.Error("shm_user not found.uid=%d", mybuf.Session)
			mybuf.Command = config.SC_ERROR
			mybuf.Code = config.NOTFOUND
			mybuf.WriteTo(conn, nil)
			return
		}
	}
	switch mybuf.Command {
	case config.SC_CREATE_BATTLE: // 创建战斗
		mybuf.Command = config.SC_CREATE_BATTLE
		BattleCreate(conn, mybuf, fd)
	default:
		return
	}
	return
}

func Heart(conn net.Conn, mybuf *mysock.SockBuf) uint16 {
	mybuf.Command = config.CSC_Heart
	u := &pb.CSC_Heart{
		Timenow: sharemem.Myshm.Time_now,
	}
	data, _ := proto.Marshal(u)
	return mybuf.WriteTo(conn, data)
}

func ActivePush(mybuf *mysock.SockBuf, user_map *map[int64]*sharemem.ShmUser) {
	// 遍历所有战斗，判断是否推送消息
	/*for k,v := range fight_map {
	  }*/
}
